import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

class Solution {
    public List<List<Integer>> permuteUnique(int[] nums) {
        Arrays.sort(nums);
        int n = nums.length;
        path = new ArrayList<>();
        ret = new ArrayList<>();
        visited = new boolean[n];
        dfs(nums);
        return ret;
    }
    public List<Integer> path;
    public List<List<Integer>> ret;
    public boolean[] visited;
    public void dfs(int[] nums) {
        if(path.size() == nums.length) {
            ret.add(new ArrayList<>(path));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if(!visited[i] && (i == 0 || nums[i] != nums[i-1] || visited[i-1])) {
                path.add(nums[i]);
                visited[i] = true;
                dfs(nums);
                visited[i] = false;
                path.remove(path.size()-1);
            }
        }
    }
}